<?php

namespace addons\facrm\controller\facrm\apps;

use addons\facrm\library\BackendApi;

use think\Queue;
use think\Validate;

/**
 * 邮件模板
 * @icon fa fa-tags
 */
class Email extends BackendApi
{

    protected $key = "emalitpl_setting_lists";
    protected $addon_config = array();
    protected $noNeedRight = ['selectpage'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\Setting();
        $this->request->filter(['strip_tags']);

    }


    /**
     * 发邮件|获取邮件模板
     * @ApiMethod (POST|GET)
     * @ApiParams(name="data", type="string", required=true, description="json格式，types对象：customer，business，contacts，clues。typesid：对应的对象ID【get|post】")
     * @ApiParams(name="row[title]", type="string", required=true, description="邮件标题【post】")
     * @ApiParams(name="row[email]", type="string", required=true, description="邮箱【post】")
     * @ApiParams(name="row[content]", type="string", required=true, description="邮件内容【post】")
     * @ApiParams(name="email_id", type="int", required=flase, description="邮件模板ID，【get】")
     * @ApiBody ("post 发送，get获取邮件模板内容。")
     */
    public function send()
    {


        $data = $this->request->request('data');
        $data = json_decode($data, true);

        $types_data = array();//发送对象数据，如客户，联系人
        if ($data && $data['types']) {
            $auth = new \addons\facrm\library\Auth();
            //TODO 还可以精简，为了明了，暂时不做
            switch ($data['types']) {
                case "customer":
                    $custModel = new \app\admin\model\facrm\Customer();
                    $types_data = $custModel->find($data['typesid']);

                    if (!$auth->checkCustomerAuth($types_data, $this->auth)) {
                        $this->error(__('您没有权限'));
                    }
                    $types_data = $types_data->toArray();
                    break;
                case "business":
                    $bModel = new \app\admin\model\facrm\Business();
                    $b_data = $bModel->find($data['typesid']);
                    $types_data=$b_data->customer?$b_data->customer:'';
                    if (!$auth->checkCustomerAuth($types_data, $this->auth)) {
                        $this->error(__('您没有权限'));
                    }
                    $types_data = $types_data->toArray();
                    break;
                case "contacts":
                    $contactsModel = new \app\admin\model\facrm\customer\Contacts();
                    $types_data = $contactsModel->find($data['typesid']);
                    if (!$types_data) break;
                    if (!$auth->checkCustomerAuth($types_data['customer_id'], $this->auth)) {
                        $this->error(__('您没有权限'));
                    }
                    break;
                case "clues":
                    $custModel = new \app\admin\model\facrm\Clues();
                    $types_data = $custModel->find($data['typesid']);
                    if (!$auth->checkCluesAuth($types_data, $this->auth)) {
                        $this->error(__('您没有权限'));
                    }
                    $types_data = $types_data->toArray();
                    break;
                default:
                    break;
            }
        }
        $email_id = $this->request->param('email_id', '', 'intval');
        $config_row = array();
        if ($email_id) {
            $config_row = $this->model->where('key', $this->key)->find($email_id);
            $values=$config_row['values'] = json_decode($config_row['values'], true);
            if ( isset($values['content'])){
                //参数格式化
                $values['content']=(__($values['content'],$types_data));
                $config_row['values']=$values;
            }

        }

        if ($this->request->isPost()) {
            $this->request->filter([]);
            $row = $this->request->post('row/a');
            if ($row['email']) {
                if (!Validate::is($row['email'], "email")) {
                    $this->error(__('邮箱有误'));
                }

                //邮件队列
                $data = array_merge($data,[
                    'subject' => $row['title'],
                    'to' => $row['email'],
                    'message' => __($row['content'], $types_data),
                ]);

                Queue::push("addons\\facrm\\library\\queue\\EmailJob", $data);
                //邮件队列end
                if (true) {
                    //param_data types类型如customer,contacts| typesid对应的ID
                    //send_data发送邮件的内容
                    //types_data 当前对象的数据
                    $row['create_user_id'] = $this->auth->id;//用于标明是谁发送的
                    $row['record_type']=isset($config_row['values']['record_type']) ? $config_row['values']['record_type'] : 0;//跟进类型
                    hook("facrm_send_email_success", array('param_data' => $data, 'send_data' => $row, 'types_data' => $types_data));
                    $this->success();
                }
            } else {
                $this->error(__('Invalid parameters'));
            }
        }

        return $this->success('', ['row' => $config_row, 'types_data' => $types_data]);
    }



    /**
     * 批量发邮件|获取邮件模板
     * @ApiMethod (POST|GET)
     * @ApiParams(name="data", type="string", required=true, description="json格式，types对象：customer，business，contacts，clues。typesid：对象集合ID，多个以逗号隔开【get|post】")
     * @ApiParams(name="row[title]", type="string", required=true, description="邮件标题【post】")
     * @ApiParams(name="row[email]", type="string", required=true, description="邮箱【post】")
     * @ApiParams(name="row[content]", type="string", required=true, description="邮件内容【post】")
     * @ApiParams(name="email_id", type="int", required=flase, description="邮件模板ID，【get】")
     * @ApiBody ("post 发送，get获取邮件模板内容")
     */

    public function sends()
    {

        $data = $this->request->param('data');
        $data = json_decode($data, true);

        if ($this->request->isPost()) {
            $row = $this->request->post('row/a');

            //TODO 未判断选择客户和联系人的权限
            //邮件队列
            $row['create_user_id']=$this->auth->id;
            $data =array_merge($data,$row);
            Queue::push("addons\\facrm\\library\\queue\\EmailsJob", $data);
            $this->success();
        }
        $types_data = array();//发送对象数据，如客户，联系人
        if ($data && $data['types']) {
            switch ($data['types']) {
                case "customer":
                    $custModel = new \app\admin\model\facrm\Customer();
                    $types_data = $custModel->where('id','in',$data['typesid'])->find();
                    $types_data = $types_data->toArray();
                    break;
                case "contacts":
                    $contactsModel = new \app\admin\model\facrm\customer\Contacts();
                    $types_data = $contactsModel->where('id','in',$data['typesid'])->find();
                    break;
                case "clues":
                    $custModel = new \app\admin\model\facrm\Clues();
                    $types_data = $custModel->where('id','in',$data['typesid'])->find($data['typesid']);
                    $types_data = $types_data->toArray();
                    break;
                default:
                    break;
            }
        }
        $email_id = $this->request->param('email_id', '', 'intval');
        $row = array();
        if ($email_id) {
            $row = $this->model->where('key', $this->key)->find($email_id);
            $values=$row['values'] = json_decode($row['values'], true);
            if ( isset($values['content'])){
                //参数格式化
                $values['content']=(__($values['content'],$types_data));
                $row['values']=$values;
            }
        }
        return $this->success('', ['row' => $row,'types_data'=>$types_data]);
    }

    /**
     * 选择邮件模板
     * @ApiInternal
     * @return \think\response\Json
     */
    public function selectpage()
    {
        $this->request->request(['custom' => ['key' => $this->key,'status'=>1]]);
        return parent::selectpage(); // TODO: Change the autogenerated stub
    }
}